package com.bawei.module_login.vm

import com.bawei.lib_common.vm.BaseViewModel
import com.bawei.module_login.inient.LoginIntent
import com.bawei.module_login.re.LoginRepository
import com.bawei.module_login.status.LoginStatus
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository:LoginRepository):BaseViewModel<LoginIntent>(){


    private val _uiStateFlow = MutableStateFlow<LoginStatus>(LoginStatus.LoadEmpty)
    val uiStateFlow: StateFlow<LoginStatus> = _uiStateFlow.asStateFlow()

    override fun dispatchIntent(intent: LoginIntent) {
        when(intent){
            is LoginIntent.LoadLogin -> getAuthorById(intent.username,intent.password)
        }
    }
    private fun getAuthorById(uasename: String,password:String){
        mViewModelScope.launch (mDispatcher) {
            repository.getAuthorId(uasename,password).collectLatest {
                if (it != null){
                    _uiStateFlow.value = LoginStatus.LoadloginSuccess(it)
                } else {
                    _uiStateFlow.value = LoginStatus.LoadloginFail("登陆失败")
                }
            }
        }
    }
}